package com.h117121.fashionshop.core.dao;

import java.text.MessageFormat;
import java.util.Date;
import java.util.List;

import org.springframework.stereotype.Repository;

import com.h117121.fashionshop.core.dao.generic.GenericDaoImpl;
import com.h117121.fashionshop.core.dom.DateQueryType;
import com.h117121.fashionshop.core.dom.Invoice;
import com.h117121.fashionshop.core.dom.Invoice.PaymentMethod;

@Repository("invoiceDao")
public class InvoiceDaoImpl extends GenericDaoImpl<Invoice, Long> implements
		InvoiceDao {

	private String queryString = "from Invoice where {0} {1} {2}";

	@SuppressWarnings("unchecked")
	@Override
	public List<Invoice> findByUsername(String username) {
		return getSessionFactory()
				.getCurrentSession()
				.createQuery(
						MessageFormat.format(queryString, "account.userName",
								"=", addSingleQuote(username))).list();
	}

	@Override
	public List<Invoice> findByDateCreated(Date date, DateQueryType type) {
		return findByDate("dateCreated", type, date);

	}

	@Override
	public List<Invoice> findByDatePaid(Date date, DateQueryType type) {
		return findByDate("datePaid", type, date);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Invoice> findByPaymentMethod(PaymentMethod method) {
		return getSessionFactory()
				.getCurrentSession()
				.createQuery(
						MessageFormat.format(queryString, "paymentMethod", "=",
								addSingleQuote(method.toString()))).list();
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Invoice> findByProductName(String name) {
		String query = "select distinct invoice from Invoice as invoice join invoice.products as product where {0} {1} {2}";
		return getSessionFactory()
				.getCurrentSession()
				.createQuery(
						MessageFormat.format(query, "lower(product.name)",
								"like", formatLikeString(name))).list();
		// return getHibernateTemplate().find(
		// MessageFormat.format(query, "product.name", "=",
		// addSingleQuote(name)));
	}
}
